import React, { FC ,useState ,useEffect } from 'react'
// 碳排放
import $axios from '@/utils/axios'
import { Select } from 'antd'

const { Option } = Select
interface MyDefinedSelectProps {
  url: string;
  params?:object;
  namekey:string;
  idkey:string;
  formatIdKey:(arg0?: unknown) => void;
  requestMethod:string;
  placeholder?: string;
  value?: string;
  onChange?: (arg0: unknown) => void;
  type?:string //1 分页  2  list
  multiple?:boolean //多选
}
const MyDefinedSelect: FC<MyDefinedSelectProps> = (props:MyDefinedSelectProps) => {
  const [list,setList] = useState([]);
  const {
    placeholder = '请选择',
    value,
    onChange = () => {},
    formatIdKey,
    type,
    multiple
  } = props
  const handerChange = (val: string | number): void => {
    // console.log(val);
    onChange(val)
  }
  useEffect(()=>{
    let params:object = {
      ...{
        'pageNum': 1,
        'pageSize': 10000
      },
      ...props['params']
    }
    let method = props['requestMethod'];
    $axios[method](props['url'],params).then((res)=>{
      let list = [];
      if(type==='1'){
        list = res['data']['list']?res['data']['list']:[];
      }else{
        list = res['data']?res['data']:[];
      }
      // console.log(list);
      list.map((e,i)=>{
        let name = props['namekey'];
        let key = props['idkey'];
        list[i]['name'] = e[name];
        list[i]['key'] = e[key];
      })
      setList(list);
    })
  },[])
    return  multiple?<Select
    onChange={handerChange}
    optionFilterProp="children"
    placeholder={placeholder}
    value={value}
    style={{minWidth:'150px'}}
    mode="multiple"
>
  {list.map((item) => (
    <Option key={item.key} title={item.name} value={item.key}>
      {item.name}
    </Option>
  ))}

</Select>:<Select
        onChange={handerChange}
        optionFilterProp="children"
        placeholder={placeholder}
        value={value}
        style={{minWidth:'150px'}}

    >
       <Option value=''>请选择</Option>
      {list.map((item) => (
        <Option key={item.key} title={item.name} value={item.key}>
          {item.name}
        </Option>
      ))}

    </Select>
}

MyDefinedSelect.defaultProps={
  url:'',
  params:{},
  namekey:'name',
  idkey:'id',
  requestMethod:'get',
  formatIdKey:(key)=>{return key},
  type:'1',
  multiple:false
}
export default MyDefinedSelect





